package main

import (
	"math/rand"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var ran *rand.Rand = rand.New(rand.NewSource(time.Now().Unix()))
var dbm *sqlx.DB
var dbs []*sqlx.DB

func setDB(db *sqlx.DB) {
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(200)
}

func DBConnect() {
	dbmstr := "bxa10:bxa10@tcp(127.0.0.1:3306)/bxa10?charset=utf8&parseTime=True&loc=Asia%2fShanghai"
	// dbmstr := "goAdminSushe9:goAdminSushe9@/goadminsushe9?charset=utf8&parseTime=True&loc=Asia%2fShanghai"
	dbsstrs := []string{dbmstr}
	//主
	// 全局变量数据初始化
	thedbm, err := sqlx.Connect("mysql", dbmstr)
	if err != nil {
		panic(err)
	}
	setDB(thedbm)
	dbm = thedbm

	//从
	for _, dbsstr := range dbsstrs {
		thedbs, err := sqlx.Connect("mysql", dbsstr)
		if err != nil {
			panic(err)
		}
		setDB(thedbs)
		dbs = append(dbs, thedbs)
	}
}

func DBMaster() *sqlx.DB {
	return dbm
}

func DBSlaveRand() *sqlx.DB {
	return dbs[ran.Intn(len(dbs))]
}
